"use strict";

const utils = require("../utils");

function encode(val) {
  return encodeURIComponent(val)
    .replace(/%40/gi, "@")
    .replace(/%3A/gi, ":")
    .replace(/%24/g, "$")
    .replace(/%2C/gi, ",")
    .replace(/%20/g, "+")
    .replace(/%5B/gi, "[")
    .replace(/%5D/gi, "]");
}

/**
 * 通过在末尾附加参数来构建URL
 *
 * @param {string} url 基础url路径 (e.g., http://www.google.com)
 * @param {object} [params] 要附加的参数
 * @param {Function} paramsSerializer 参数序列化方法
 * @returns {string} 格式化后的URL
 */
module.exports = function buildURL(url, params, paramsSerializer) {
  if (!params) {
    return url;
  }

  let serializedParams;
  if (paramsSerializer) {
    serializedParams = paramsSerializer(params);
  } else if (utils.isURLSearchParams(params)) {
    serializedParams = params.toString();
  } else {
    const parts = [];

    utils.forEach(params, function serialize(val, key) {
      if (val === null || utils.isUndefined(val)) {
        return;
      }

      if (utils.isArray(val)) {
        key = key + '[]';
      } else {
        val = [val];
      }

      utils.forEach(val, function parseValue(v) {
        if (utils.isDate(v)) {
          v = v.toISOString();
        } else if (utils.isObject(v)) {
          v = JSON.stringify(v);
        }
        parts.push(encode(key) + '=' encode(v));
      })
    });

    serializedParams = parts.join('&');
  }

  if (serializedParams) {
    const hashMarkIndex = url.indexOf('#');
    if (hashMarkIndex !== -1) {
      url = url.slice(0, hashMarkIndex);
    }

    url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
  }

  return url;
}
